﻿using HtmlAgilityPack;
using Newtonsoft.Json;
using Serilog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using XjjXmm.FrameWork.Cache;

namespace XjjXmm.Spider
{
    internal class FetchLinkSpider 
    {
        //https://www.zhihu.com/question/359676590/answer/1615531107

       
        private readonly ISqlSugarClient _sqlSugarClient;
        private readonly ISpider _spider;

        public FetchLinkSpider(ISqlSugarClient sqlSugarClient, ISpider spider)
        {
            _sqlSugarClient = sqlSugarClient;
            _spider = spider;
        }

        public async Task Run()
        {
            try
            {
                await foreach (var link in _spider.FetchNovelLinks())
                {

                    var isExistNovel = await _sqlSugarClient.Queryable<NovelEntity>()
                     .Where(t => t.Link == link && t.Domain == _spider.Domain)
                     .AnyAsync();

                    if (!isExistNovel)
                    {
                        var novel = await _spider.FetchNovel(link);
                        var novelEntity = new NovelEntity()
                        {
                            Title = novel.Title,
                            Author = novel.Author,
                            Category = novel.Category,
                            IsInstalment = novel.IsInstalment,
                            LastChapter = novel.LastChapter,
                            UpdateTime = novel.UpdateTime,

                            Link = link,
                            Domain = _spider.Domain,
                            FetchTime = DateTime.Now,
                            Status = 0
                        };

                        _spider.GetLogger().Debug($"新增小说： {_spider.Domain}:{novel.Title}");

                        await _sqlSugarClient.Insertable(novelEntity).ExecuteCommandAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                _spider.GetLogger().Error(ex, _spider.Domain);
                throw;
            }
            //await GetDetail("/15/15021/6803437.html");
        }

       


        private async Task GetArticle(string? url)
        {
           /* try
            {
                var link = url?.Replace(Domain, "");

                if (string.IsNullOrEmpty(link))
                {
                    throw new ArgumentNullException("url");
                }

                var existNovel = await _sqlSugarClient.Queryable<NovelEntity>()
                 .Where(t => t.Link == url && t.Domain == Domain)
                 .FirstAsync();

                if (existNovel?.IsFinished == true)
                {
                    return;
                }

                await Task.Delay(2000);


                //var htmlDoc = GetNovel(link);

                var novel = await GetNovel(link);
                novel.Link = url;

                bool hasAlreadyImport = await _sqlSugarClient.Queryable<NovelEntity>()
                     .Where(t => t.Title == novel.Title && t.Author == novel.Author && t.Domain != Domain)
                     .AnyAsync();

                if (hasAlreadyImport)
                {
                    return;
                }

                var id = 0;
                if (existNovel == null)
                {
                    id = await _sqlSugarClient.Insertable(novel).ExecuteReturnIdentityAsync();
                }
                else
                {
                    id = existNovel.Id;
                }
                //_sqlSugarClient.Saveable<Novel>(novel);
                //var charapters = GetChapters(htmlDoc);

                Logger.Debug($"小说: {novel.Title}, 作者: {novel.Author}");
                foreach (var chapter in novel.Chapters)
                {
                    //var title = chapter.title;

                    //var author = chapter.author;

                    //var chapterTitle = chapter.chapterTitle;

                    Logger.Debug($"小说: {novel.Title}, 章节：{chapter.Title}");

                    chapter.NovelId = id;


                    var isChapterExist = await _sqlSugarClient.Queryable<Chapter>().Where(t => t.Title == chapter.Title && t.NovelId == id).AnyAsync();
                    if (isChapterExist)
                    {
                        continue;
                    }

                    try
                    {
                        var content = await GetChaptersDetail(chapter.Link);
                        chapter.Content = content;
                        await _sqlSugarClient.Insertable<Chapter>(chapter).ExecuteCommandAsync();
                    }
                    catch (Exception ex)
                    {
                        Logger.Information("chapter:{}", JsonConvert.SerializeObject(chapter));
                        Logger.Error(ex, "GetChaptersDetail");
                        throw;
                    }



                    await Task.Delay(5000);
                }

                novel.Id = id;
                novel.IsFinished = true;

                await _sqlSugarClient.Updateable(novel).ExecuteCommandAsync();
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "GetArticle");
                throw;
            }*/

        }



        //protected abstract string Domain { get; }

        //protected abstract IAsyncEnumerable<string> FetchNovelLinks();

        //protected abstract Task<NovelModel> FetchNovel(string url);

        //protected abstract IAsyncEnumerable<Chapter> FetchChapters(string url);

        //protected abstract Task<string> FetchContent(string url);
    }


}
